package infoexract.exractreason.samesent.treepattern.pattern;


import java.util.Vector;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class SubTreePatternElement {
	private String cat="";
	private String token="";
	private SubTreePatternElement next=null;
	private Vector<SubTreePatternElement> tabuVector = new Vector<SubTreePatternElement>();
	public SubTreePatternElement()
	{
		
	}
	public SubTreePatternElement(String cat, String token)
	{
		this.cat = cat;
		this.token = token.toLowerCase().trim();
	}
	public void setElement(String cat, String token)
	{
		this.cat = cat;
		this.token = token.toLowerCase().trim();
	}
	public boolean isMatch(Node root)
	{
		if(this.cat.equals("")||this.token.equals("")) return false;
		NamedNodeMap attributeMap = root.getAttributes();
		Node catAttribute = attributeMap.getNamedItem("cat");
		if(!catAttribute.getNodeValue().equals(this.cat)) return false;
		if(this.token.equals("nm")) return true;
		return isSubTreeFirstTokens(root, this.token);
	}
	private static boolean isSubTreeFirstTokens(Node root, String token)
	{
		if(root.getNodeType()!=Node.ELEMENT_NODE) return false;
		if(root.getNodeName().equals("tok")) 
		{
			String firsttoken = root.getFirstChild().getNodeValue();
			firsttoken = firsttoken.toLowerCase().trim();
			if(token.equals(firsttoken)) return true;
		}
		for(Node childNode = root.getFirstChild();childNode!=null;childNode = childNode.getNextSibling())
		{
			if(childNode.getNodeType()!=Node.ELEMENT_NODE) continue;
			boolean childResult = isSubTreeFirstTokens(childNode,token);
			if(childResult) return true;
			break;
		}
		return false;
	}
	public void setNext(SubTreePatternElement next)
	{
		this.next = next;
	}
	public SubTreePatternElement getNext()
	{
		return this.next;
	}
	public void addTabuElement(SubTreePatternElement element)
	{
		this.tabuVector.add(element);
	}
	public boolean isTabu(Node root)
	{
		for(SubTreePatternElement element : this.tabuVector)
		{
			boolean ismatch = element.isMatch(root);
			if(ismatch==true) return true;
		}
		return false;
	}
}
